package cn.xinfei.xdecision.common.service.component.scorecard.impl;

import cn.xinfei.xdecision.common.dao.component.scorecard.ScorecardMapper;
import cn.xinfei.xdecision.common.model.common.PageResult;
import cn.xinfei.xdecision.common.model.common.ResponseEntityDto;
import cn.xinfei.xdecision.common.model.component.ComponentVersionVo;
import cn.xinfei.xdecision.common.model.component.ComponentVo;
import cn.xinfei.xdecision.common.model.component.CopyToFolderReqVo;
import cn.xinfei.xdecision.common.model.component.dependency.EngineNodeComponentRel;
import cn.xinfei.xdecision.common.model.component.dependency.resp.DecisionComponentDependencyResp;
import cn.xinfei.xdecision.common.model.component.guiderule.vo.RuleListReqVo;
import cn.xinfei.xdecision.common.model.component.request.ListParam;
import cn.xinfei.xdecision.common.model.component.scorecard.Scorecard;
import cn.xinfei.xdecision.common.model.component.scorecard.ScorecardVersion;
import cn.xinfei.xdecision.common.model.component.scorecard.vo.ScorecardDimensionVo;
import cn.xinfei.xdecision.common.model.component.scorecard.vo.ScorecardVersionVo;
import cn.xinfei.xdecision.common.model.component.scorecard.vo.ScorecardVo;
import cn.xinfei.xdecision.common.model.login.SessionManager;
import cn.xinfei.xdecision.common.service.common.sso.SSOService;
import cn.xinfei.xdecision.common.service.common.sso.dto.SSOUserInfoReqDto;
import cn.xinfei.xdecision.common.service.common.sso.dto.SSOUserInfoRespDto;
import cn.xinfei.xdecision.common.service.component.ComponentCommonContext;
import cn.xinfei.xdecision.common.service.component.ComponentCommonService;
import cn.xinfei.xdecision.common.service.component.dependency.EngineNodeComponentRelService;
import cn.xinfei.xdecision.common.service.component.scorecard.ScorecardService;
import cn.xinfei.xdecision.common.service.component.scorecard.ScorecardVersionService;
import cn.xinfei.xdecision.common.service.utils.CodeGenerateUtil;
import cn.xinfei.xdecision.common.utils.constant.SysConstant;
import cn.xinfei.xdecision.common.utils.enums.enginex.ComponentStatusEnum;
import cn.xinfei.xdecision.common.utils.enums.enginex.ComponentVersionStatusEnum;
import cn.xinfei.xdecision.common.utils.exception.ApiException;
import cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum;
import cn.xinfei.xdecision.common.utils.util.BeanUtilsPlus;
import cn.xinfei.xdecision.common.utils.util.FutureUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import static cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum.COMPONENT_COPY_ERROR;
import static cn.xinfei.xdecision.common.utils.exception.util.ApiExceptionUtil.exception;

/**
 * 评分卡(Scorecard) Service实现类
 */
@Service("scorecardService")
@Slf4j
public class ScorecardServiceImpl extends ServiceImpl<ScorecardMapper, Scorecard> implements ScorecardService, ComponentCommonService {

    @Resource
    private ScorecardVersionService scorecardVersionService;

    @Resource
    private ScorecardMapper scorecardMapper;

    @Resource
    private ScorecardVersionService versionService;

    @Resource
    private SSOService ssoService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private CodeGenerateUtil codeGenerateUtil;

    @Resource
    private ScorecardServiceImpl scorecardService;

    @Resource(name = "componentAsyncExecutor")
    private ExecutorService bizProcessorThreadPool;

    @Resource
    private EngineNodeComponentRelService engineNodeComponentRelService;

    /**
     * 新增
     *
     * @param scorecardVo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class, isolation = Isolation.REPEATABLE_READ)
    public Scorecard addScorecard(ScorecardVo scorecardVo) {

        Scorecard scorecard = new Scorecard();
        BeanUtils.copyProperties(scorecardVo, scorecard);
        this.checkUniqueness(scorecard);  // 校验评分卡 name versionCode 唯一性

//        SSOUser user = SessionManager.getLoginAccount();
//        scorecard.setUserId(user.getId());
//        scorecard.setAuthor(user.getId());
//        scorecard.setOrganId(user.getOrganId());

//        scorecard.setType(1);  // 1表示组织
        scorecard.setStatus(1);

        boolean saveScorecard = this.save(scorecard);

        if (!saveScorecard) {
            throw new ApiException(ErrorCodeEnum.SERVER_ERROR.getCode(), ErrorCodeEnum.SERVER_ERROR.getMessage());
        }
        List<ScorecardVersionVo> versionList = scorecardVo.getVersionList();
        if (versionList != null && versionList.size() == 1) {
            ScorecardVersionVo versionVo = versionList.get(0);
            versionVo.setScorecardCode(scorecard.getCode());
            scorecardVersionService.addVersion(versionVo);
        }
        ScorecardVo scorecardInfo = this.getScorecardInfo(scorecard.getCode());
        return scorecardInfo;
    }

    /**
     * 获取评分卡详细信息
     *
     * @param scoreCardCode
     * @return
     */
    @Override
    public ScorecardVo getScorecardInfo(String scoreCardCode) {
        ScorecardVo scorecardVo = new ScorecardVo();
        LambdaQueryWrapper<Scorecard> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(Scorecard::getCode, scoreCardCode);
        Scorecard scorecard = this.getOne(objectLambdaQueryWrapper);
        if (scorecard == null) {
            throw new ApiException(ErrorCodeEnum.DATA_IS_NOT_EXIST.getCode(), ErrorCodeEnum.DATA_IS_NOT_EXIST.getMessage());
        }
        BeanUtils.copyProperties(scorecard, scorecardVo);
        scorecardVo.setVersionList(scorecardVersionService.queryVersionListByScorecardId(scoreCardCode));
        return scorecardVo;
    }

    /**
     * 修改评分卡 状态 (批量)
     *
     * @param ids    id集合
     * @param status 状态
     */
    @Override
    public void updateScorecardStatus(List<Long> ids, Integer status) {

        LambdaUpdateWrapper<Scorecard> scorecardUpdateWrapper = new LambdaUpdateWrapper<>();
        scorecardUpdateWrapper.in(Scorecard::getId, ids);
        scorecardUpdateWrapper.set(Scorecard::getStatus, status);

        boolean update = this.update(scorecardUpdateWrapper);
        if (!update) {
            throw new ApiException(ErrorCodeEnum.SERVER_ERROR.getCode(), ErrorCodeEnum.SERVER_ERROR.getMessage());
        }
    }

    @Override
    public void logicalDeleteScorecards(List<Long> ids) {
        this.removeByIds(ids);
    }

    @Override
    public List<Long> queryByFolderId(Long folderId) {
        return scorecardMapper.selectIdsByFolderId(folderId);
    }

    /**
     * 校验评分卡 name versionCode 唯一性
     *
     * @param scorecard Scorecard实体
     */
    private void checkUniqueness(Scorecard scorecard) {

        // 后期可以改为sql语句形式
        // SELECT COUNT(`id`) FROM `t_scorecard` WHERE `name` = #{name};
        LambdaQueryWrapper<Scorecard> lqwName = new LambdaQueryWrapper<>();
        lqwName.eq(Scorecard::getName, scorecard.getName());
        if (scorecard.getId() != null) {
            lqwName.ne(Scorecard::getId, scorecard.getId());
        }
        int countName = this.count(lqwName);
        if (countName > 0) {
            throw new ApiException(ErrorCodeEnum.SCORECARD_NAME_REPEAT.getCode(), ErrorCodeEnum.SCORECARD_NAME_REPEAT.getMessage());
        }

        // 后期可以改为sql语句形式
        // SELECT COUNT(`id`) FROM `t_scorecard` WHERE `versionCode` = #{versionCode} AND `id` != #{id};
        LambdaQueryWrapper<Scorecard> lqwCode = new LambdaQueryWrapper<>();
        lqwCode.eq(Scorecard::getCode, scorecard.getCode());
        if (scorecard.getId() != null) {
            lqwCode.ne(Scorecard::getId, scorecard.getId());
        }
        int countCode = this.count(lqwCode);
        if (countCode > 0) {
            throw new ApiException(ErrorCodeEnum.SCORECARD_CODE_REPEAT.getCode(), ErrorCodeEnum.SCORECARD_CODE_REPEAT.getMessage());
        }
    }


    @Override
    public ScorecardVo queryExecuteScorecard(Long versionId) {
        ScorecardVersionVo version = versionService.queryById(versionId);
        String scorecardCode = version.getScorecardCode();
        LambdaQueryWrapper<Scorecard> lqwCode = new LambdaQueryWrapper<>();
        lqwCode.eq(Scorecard::getCode, scorecardCode);
        Scorecard scorecard = this.getOne(lqwCode);
        ScorecardVo scorecardVo = new ScorecardVo();
        BeanUtils.copyProperties(scorecard, scorecardVo);
        scorecardVo.setExecuteVersion(version);
        return scorecardVo;
    }

    @Override
    public ScorecardVo queryById(Long id) {
        ScorecardVo scorecardVo = new ScorecardVo();
        //主表信息
        Scorecard scorecard = this.getById(id);
        if (Objects.isNull(scorecard)) {
            return scorecardVo;
        }
        BeanUtils.copyProperties(scorecard, scorecardVo);
        //规则状态描述
        scorecardVo.setStatusDesc(Objects.requireNonNull(ComponentStatusEnum.get(scorecardVo.getStatus())).getName());
        //全部版本信息
        List<ScorecardVersionVo> scorecardVersionVos = versionService.queryVersionByScorecardCodes(
                Collections.singletonList(scorecardVo.getCode()), null);
        if (CollectionUtils.isEmpty(scorecardVersionVos)) {
            return scorecardVo;
        }
        //当前版本
        ScorecardVersionVo scorecardVersionVo = scorecardVersionVos.stream()
                .max(Comparator.comparing(ScorecardVersionVo::getId)).orElse(null);
        if (Objects.isNull(scorecardVersionVo)) {
            return scorecardVo;
        }
        scorecardVo.setLastVersionStatus(scorecardVersionVo.getStatus())
                //最新版本状态描述
                .setLastVersionStatusDesc(Objects.requireNonNull(ComponentVersionStatusEnum.get(scorecardVersionVo.getStatus())).getName())
                //当前版本
                .setLastVersion(scorecardVersionVo.getVersionNo())
                //版本说明
                .setVersionDesc(scorecardVersionVo.getDescription())
                //是否存在新建版本
                .setIsNewVersion(scorecardVersionVos.stream().anyMatch(x -> Objects.equals(x.getStatus(), ComponentVersionStatusEnum.NEW.getStatus())))
                .setVersionList(Lists.newArrayList(scorecardVersionVo));
        return scorecardVo;
    }

    @Override
    public ResponseEntityDto<PageResult<List<ScorecardVo>, Scorecard>> queryByEntity(ListParam listParam) {
        List<Long> orgIdList = SessionManager.getLoginAccount().getOrgIdList();
        if (CollectionUtils.isEmpty(orgIdList)) {
            return ResponseEntityDto.success(new PageResult<>());
        }
        //决策树
        LambdaUpdateWrapper<Scorecard> lbd = new LambdaUpdateWrapper<>();
        if (StringUtils.isNotEmpty(listParam.getCondition())) {
            lbd.eq(Scorecard::getCode, listParam.getCondition())
                    .or().like(Scorecard::getName, listParam.getCondition());
        }
        if (Objects.nonNull(listParam.getFolderId())) {
            lbd.eq(Scorecard::getFolderId, listParam.getFolderId());
        }
        lbd.in(Scorecard::getOrganId, orgIdList);
        PageMethod.startPage(listParam.getPageNo(), listParam.getPageSize());
        //排序按照启用，更新时间倒叙
        List<Scorecard> scorecards = this.list(lbd.last("order by status = 1 desc,updated_time desc"));
        if (CollectionUtils.isEmpty(scorecards)) {
            return PageResult.success(new ArrayList<>(), new PageInfo<>());
        }
        PageInfo<Scorecard> pageInfo = new PageInfo<>(scorecards);
        List<ScorecardVo> scorecardVos = BeanUtilsPlus.copyElements(scorecards, ScorecardVo::new);
        //版本号
        List<ScorecardVersionVo> scorecardVersionVos = versionService.queryVersionByScorecardCodes(
                scorecardVos.stream().map(ScorecardVo::getCode).collect(Collectors.toList()), null);
        //最新版本号
        Map<String, List<ScorecardVersionVo>> versionMap = scorecardVersionVos
                .stream().collect(Collectors.groupingBy(ScorecardVersionVo::getScorecardCode));
        //更新人信息
        SSOUserInfoReqDto ssoUserInfoReqDto = new SSOUserInfoReqDto();
        ssoUserInfoReqDto.setId(new ArrayList<>(
                scorecards.stream().map(Scorecard::getUpdateUserId).collect(Collectors.toSet())));
        Map<Long, String> sysMap = ssoService.getUserInfos(ssoUserInfoReqDto).stream()
                .collect(Collectors.toMap(SSOUserInfoRespDto::getId, SSOUserInfoRespDto::getName));
        scorecardVos.forEach(x -> {
                    List<ScorecardVersionVo> versionVos = versionMap.getOrDefault(x.getCode(), new ArrayList<>());
                    //状态描述
                    x.setStatusDesc(Objects.requireNonNull(ComponentStatusEnum.get(x.getStatus())).getName())
                            //更新人信息
                            .setUpdatedUserName(sysMap.getOrDefault(x.getUpdateUserId(), SysConstant.EMPTY_STRING))
                            //版本集合
                            .setVersionList(versionVos);
                    //最新版本号
                    Long lastVersion = versionVos.stream()
                            .max(Comparator.comparing(ScorecardVersionVo::getVersionNo))
                            .map(ScorecardVersionVo::getVersionNo).orElse(0L);
                    x.setLastVersion(lastVersion).setLastVersionDesc("V" + lastVersion);
                }
        );
        return PageResult.success(scorecardVos, pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long checkAndSaveScorecard(ScorecardVo scorecardVo) {
        if (StringUtils.isEmpty(scorecardVo.getName())) {
            throw new ApiException(ErrorCodeEnum.NAME_CAN_NOT_BE_NULL);
        }
        //只能修改最新版本状态为‘新建’的规则
        if (!CollectionUtils.isEmpty(scorecardVo.getVersionList())) {
            ScorecardVersionVo scorecardVersionVo = scorecardVo.getVersionList().get(0);
            if (!Objects.equals(scorecardVersionVo.getStatus(), ComponentVersionStatusEnum.NEW.getStatus())) {
                throw new ApiException(ErrorCodeEnum.DECISION_SAVE_PRE_CHECK_ERROR_001.getCode(),
                        ErrorCodeEnum.DECISION_SAVE_PRE_CHECK_ERROR_001.getMessage());
            }
            //判断当前版本的状态和传进来的状态是否一致
            checkVersionStatus(scorecardVersionVo);
            scorecardVo.getVersionList().forEach(version -> {
                if (!CollectionUtils.isEmpty(version.getScorecardDimension())) {
                    version.getScorecardDimension().forEach(ScorecardDimensionVo::recursionNodeType);
                }
            });
        }
        //scorecardVo.setStatus(ComponentStatusEnum.NEW.getStatus());
        //保存
        saveScorecard(scorecardVo);
        return scorecardVo.getId();
    }

    private void checkVersionStatus(ScorecardVersionVo scorecardVersionVo) {
        if (Objects.nonNull(scorecardVersionVo.getId()) && Objects.nonNull(scorecardVersionVo.getStatus())) {
            ScorecardVersion scorecardVersion = versionService.getById(scorecardVersionVo.getId());
            if (!Objects.equals(scorecardVersion.getStatus(), scorecardVersionVo.getStatus())) {
                log.error("传进来的版本状态和数据库中不一致，入参==》{}", JSON.toJSONString(scorecardVersion));
                throw new ApiException(ErrorCodeEnum.PARAMS_EXCEPTION.getCode(),
                        ErrorCodeEnum.PARAMS_EXCEPTION.getMessage());
            }
        }
    }

    @Override
    public void copyScorecard(CopyToFolderReqVo req) {
        //查询决策树主表信息
        List<Scorecard> scorecards = this.listByIds(req.getIds());
        if (CollectionUtils.isEmpty(scorecards)) {
            return;
        }
        List<Future<Void>> allFutureList = Lists.newArrayList();
        List<String> errorCodeList = new CopyOnWriteArrayList<>();
        scorecards.forEach(x -> allFutureList.add(CompletableFuture.runAsync(() -> {
            x.setUpdateUserId(null);
            x.setUpdatedTime(null);
            //查询规则
            ScorecardVo scorecardVo = BeanUtilsPlus.copyProperties(x, ScorecardVo::new);
            scorecardVo.setName(req.getNamePrefix() + scorecardVo.getName() + req.getNameSuffix());
            scorecardVo.setFolderId(req.getFolderId());
            scorecardVo.setId(null);
            //查询全部版本信息
            List<Long> versionIds =
                    versionService.queryVersionByScorecardCodes(Collections.singletonList(scorecardVo.getCode()), null)
                            .stream().map(ScorecardVersionVo::getId).collect(Collectors.toList());
            //查询明细
            List<ScorecardVersionVo> versionVos =
                    versionIds.stream().map(id -> {
                        ScorecardVersionVo versionVo = versionService.queryById(id);
                        versionVo.recurrenceSetIdIsNull();
                        return versionVo;
                    }).collect(Collectors.toList());
            scorecardVo.setVersionList(versionVos);
            transactionTemplate.execute(status -> {
                try {
                    scorecardVo.setCode(codeGenerateUtil.generateYMDCode(SysConstant.PFK_PREFIX, null));
                    scorecardService.saveScorecard(scorecardVo);
                    return Boolean.TRUE;
                } catch (Exception e) {
                    status.setRollbackOnly();
                    log.error("评分卡复制失败，具体信息==>{}", JSON.toJSONString(x), e);
                    errorCodeList.add(x.getCode());
                    return Boolean.FALSE;
                }
            });
        }, bizProcessorThreadPool)));
        allFutureList.forEach(x -> FutureUtils.futureGet(x, ErrorCodeEnum.DECISION_COPY_ERROR));
        if (!CollectionUtils.isEmpty(errorCodeList)) {
            throw exception(COMPONENT_COPY_ERROR, errorCodeList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveScorecard(ScorecardVo scorecardVo) {
        if (Objects.isNull(scorecardVo.getId())) {
            //初始化基本参数
            initParam(scorecardVo);
        }
        //拷贝VO到Info对象
        Scorecard scorecard = BeanUtilsPlus.copyProperties(scorecardVo, Scorecard::new);
        if (Objects.nonNull(scorecard.getId())) {
            scorecard.setCode(null);
        }
        scorecard.setOrganId(SessionManager.getLoginAccount().getOrganId());
        boolean save = this.saveOrUpdate(scorecard);
        scorecardVo.setId(scorecard.getId());
        if (!save) {
            throw new ApiException(ErrorCodeEnum.DECISION_SAVE_ERROR.getCode(), ErrorCodeEnum.DECISION_SAVE_ERROR.getMessage());
        }
        List<ScorecardVersionVo> versionList = scorecardVo.getVersionList();

        if (!CollectionUtils.isEmpty(versionList)) {
            AtomicLong at = new AtomicLong();
            versionList.forEach(x -> {
                x.setScorecardCode(scorecardVo.getCode());
                if (Objects.isNull(x.getId())) {
                    x.setOrganId(SessionManager.getLoginAccount().getOrganId());
                    x.setVersionNo(at.incrementAndGet());
                }
            });
            //保存版本
            versionService.addVersionList(versionList);
        }
    }

    //新插入数据的准备工作
    private void initParam(ScorecardVo scorecardVo) {
        if (this.count(new LambdaQueryWrapper<Scorecard>()
                .eq(Scorecard::getName, scorecardVo.getName())
                .eq(Scorecard::getFolderId, scorecardVo.getFolderId())) > 0) {
            throw new ApiException(ErrorCodeEnum.DECISION_NAME_REPEAT.getCode(), ErrorCodeEnum.DECISION_NAME_REPEAT.getMessage());
        }
        scorecardVo.setOrganId(SessionManager.getLoginAccount().getOrganId());
    }

    @Override
    public void updateScorecard(List<Long> ids, Integer status, String errorMsg) {
        List<Scorecard> scorecards = this.listByIds(ids);
        String errInfo = scorecards.stream()
                .filter(x -> Objects.equals(x.getStatus(), status))
                .map(Scorecard::getCode).collect(Collectors.joining(SysConstant.COMMA));
        if (StringUtils.isNotEmpty(errInfo)) {
            throw new ApiException(
                    ErrorCodeEnum.DECISION_UPDATE_ERROR.getCode()
                    , ErrorCodeEnum.DECISION_UPDATE_ERROR.getMessage() + "," + errorMsg + ",评分卡规则编号：" + errInfo);
        }

        //停用时需校验是否被决策流依赖
        if (ComponentStatusEnum.DISABLE.getStatus().equals(status)) {
            List<EngineNodeComponentRel> dependencies =
                    engineNodeComponentRelService.getRelByComponentCode(scorecards.stream().map(Scorecard::getCode).collect(Collectors.toList()));

            if (!CollectionUtils.isEmpty(dependencies)) {
                throw exception(
                        ErrorCodeEnum.COMPONENT_STATUS_UPDATE_ERROR,
                        "存在依赖关系",
                        dependencies.stream()
                                .map(EngineNodeComponentRel::getComponentCode)
                                .distinct()
                                .collect(Collectors.joining(SysConstant.COMMA)));
            }
        }

        Scorecard scorecard = new Scorecard();
        scorecard.setStatus(status);
        this.update(scorecard, new LambdaQueryWrapper<Scorecard>().in(Scorecard::getId, ids));
    }

    @Override
    public Boolean hasNewVersion(String ruleCode) {
        return !versionService.queryVersionByScorecardCodes(
                Collections.singletonList(ruleCode), ComponentVersionStatusEnum.NEW.getStatus()).isEmpty();
    }

    @Override
    public List<ComponentVo> listComponentInfoByIds(String ids) {
        //主表信息
        List<Scorecard> scorecards = this.listByIds(Arrays.asList(ids.split(SysConstant.COMMA)));
        if (CollectionUtils.isEmpty(scorecards)) {
            return new ArrayList<>();
        }
        Map<String, List<ScorecardVersion>> collect = versionService.queryVersionByScorecardCodes(
                scorecards.stream().map(Scorecard::getCode).collect(Collectors.toList()), ComponentVersionStatusEnum.ENABLE.getStatus()).stream()
                .collect(Collectors.groupingBy(ScorecardVersion::getScorecardCode));
        if (collect.isEmpty()) {
            return new ArrayList<>();
        }
        List<ComponentVo> componentVos = BeanUtilsPlus.copyElements(scorecards, ComponentVo::new);
        componentVos.forEach(x -> {
                    List<ComponentVersionVo> componentVersionVos =
                            BeanUtilsPlus.copyElements(collect.get(x.getCode()), ComponentVersionVo::new);
                    ComponentCommonContext.swapVersionNoDesc(componentVersionVos);
                    x.setVersionList(componentVersionVos)
                            .setStatusDesc(Objects.requireNonNull(ComponentStatusEnum.get(x.getStatus())).getName());
                }
        );
        return componentVos;
    }

    @Override
    public List<DecisionComponentDependencyResp> getComponentCodeByVarCodes(List<String> varCodes) {
        return scorecardMapper.getComponentCodeByVarCodes(varCodes);
    }

    @Override
    public List<String> getFieldCodesByComponentCodes(List<ComponentVo> componentVoList) {
        if (CollectionUtils.isEmpty(componentVoList)) {
            return Collections.emptyList();
        }
        return scorecardMapper.getFieldCodesByConditions(componentVoList);
    }

    @Override
    public List<ComponentVo> listComponentInfoByCon(RuleListReqVo ruleListReqVo) {
        return scorecardMapper.pageComponentInfoByCon(ruleListReqVo);
    }
}
